package org.activequant.tradesystem.ib;

import java.util.Map;

import org.activequant.calendar.IExchangeCalendar;
import org.activequant.core.types.TimeStamp;
import org.activequant.math.algorithms.Interval;
import org.apache.log4j.Logger;

import com.ib.algokit.InstrumentAnalyzer;

public class SeriesSpecHelper {
	private final static Logger log = Logger.getLogger(SeriesSpecHelper.class); 
	
//	final IHolidayCalendar holidayCalendar = CalendarFactory.getInstance().getCalendar(USMarketsHolidayCalendarSettings.getInstance());
//	final IExchangeCalendar exchangeCalendar = CalendarFactory.getInstance().getCalendar(NYSECalendarSettings.getInstance(), holidayCalendar);

	
	public static long getTotalTradingSecondsInBetween(TimeStamp from,TimeStamp to,IExchangeCalendar exchangeCalendar){
		if(from.isAfter(to)){
			throw new IllegalArgumentException("start of interval cannot be after end of interval");
		}
		Map<TimeStamp, Interval<TimeStamp>> tradingHours=exchangeCalendar.getTradingHours(from, to);
		long totalTradingNanosInBetween=0L;
		for(Interval<TimeStamp> interval:tradingHours.values()){
			TimeStamp fromInterval=interval.from;
			TimeStamp toInterval=interval.to;
			long duration=toInterval.getNanoseconds()-fromInterval.getNanoseconds();
			if(duration>0){
				totalTradingNanosInBetween+=duration;
			}else if(duration<0){
				log.warn("something's fishy here, interval duration can't be negative");
			}
		}
		if(totalTradingNanosInBetween>0){
			long totalTradingSecondsInBetween=totalTradingNanosInBetween/InstrumentAnalyzer.ONE_SECOND;//from nanos to seconds
			return totalTradingSecondsInBetween;
		}else{
			log.debug("no trading period at all");
			return 0;
		}		
	}

}
